<template>
  <el-dialog :title="titleMap[mode]" v-model="visible" :width="330" destroy-on-close @closed="$emit('closed')">
    <el-form :model="form" :rules="rules" ref="dialogForm" label-width="80px" label-position="left">
      <el-form-item label="编码" prop="dictKey" :disabled="mode==='update'">
        <el-input v-model="form.dictKey" clearable placeholder="字典编码" :disabled="mode==='update'"></el-input>
      </el-form-item>
      <el-form-item label="字典名称" prop="title">
        <el-input v-model="form.title" clearable placeholder="字典显示名称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElAlert } from 'element-plus'
import http from "@/utils/request.js";

// 定义emit
const emit = defineEmits(['success', 'closed'])

// 响应式数据
const mode = ref('add')
const titleMap = reactive({
  create: '新增字典',
  update: '编辑字典'
})
const visible = ref(false)
const isSaveing = ref(false)
const dialogForm = ref(null)

const form = reactive({
  id: "",
  dictKey: "",
  title: "",
  parentId: ""
})

const rules = reactive({
  dictKey: [
    {required: true, message: '请输入编码'}
  ],
  title: [
    {required: true, message: '请输入字典名称'}
  ]
})

const dic = ref([])
const dicProps = reactive({
  value: "id",
  label: "name",
  emitPath: false,
  checkStrictly: true
})

// 获取字典列表
const getDic = async () => {
  try {
    const res = await $API.system.dic.tree.get()
    dic.value = res.data
  } catch (error) {
    console.error('获取字典列表失败:', error)
  }
}

// 显示对话框
const open = (dialogMode = 'create') => {
  mode.value = dialogMode
  visible.value = true
  return { open }
}

// 表单提交方法
const submit = () => {
  dialogForm.value?.validate(async (valid) => {
    if (valid) {
      isSaveing.value = true
      try {
        const res = await http.post(`/dict/${mode.value}`, form)
        isSaveing.value = false
        if (res.code === 200) {
          emit('success', form, mode.value)
          visible.value = false
          ElMessage.success("操作成功")
        } else {
          ElAlert(res.msg, "提示", {type: 'error'})
        }
      } catch (error) {
        isSaveing.value = false
        console.error('提交失败:', error)
      }
    }
  })
}

// 表单注入数据
const setData = (data) => {
  form.id = data.id
  form.dictKey = data.dictKey
  form.title = data.title
  mode.value = 'update'

  // 可以和上面一样单个注入，也可以像下面一样直接合并进去
  // Object.assign(form, data)
}

// 组件挂载时获取字典数据
onMounted(() => {
  getDic()
})

// 暴露方法给父组件使用
defineExpose({
  open,
  setData
})
</script>

<style>
</style>
